package conson.tech.manage.common.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: EntityUtils
 * Description:
 * Author: HXL
 * Date: 2020/3/12 4:13 下午
 * Version: 1.0
 */
@Slf4j
public class EntityUtils {

    /**
     * Title: 将DTO转化成VO
     * Description:
     * @param source
     * @param clazz
     * @return: java.util.List
     * Company: GX
     * Author HXL
     * Date 2020/3/12 4:32 下午
     */
    public static List listToList(List source , Class clazz){
        if (source == null || source.isEmpty()){
            return new ArrayList<>();
        }
        List list = new ArrayList<>();
        try {
            for (int i = 0 ; i < source.size(); i++ ){
                Object o = clazz.newInstance();
                BeanUtils.copyProperties(source.get(i), o);
                list.add(o);
            }
        } catch (Exception e) {
           log.error("EntityUtils--> listToList fail.",e);
        }
        return list;
    }
    public static Page pageToPage(Page source , Class clazz){
        if (source == null ){
            return new Page<>();
        }
        Page page = new Page();
        List list = new ArrayList<>();
        List records = source.getRecords();
        BeanUtils.copyProperties(source, page);
        if (records == null || records.isEmpty()){
            return page;
        }
        try {
            for (int i = 0 ; i < records.size(); i++ ){
                Object o = clazz.newInstance();
                BeanUtils.copyProperties(records.get(i), o);
                list.add(o);
            }
        } catch (Exception e) {
            log.error("EntityUtils--> pageToPage fail.",e);
        }
        page.setRecords(list);
        page.setTotal(list.size());
        return page;
    }

    public static Object beanToBean(Object source , Class clazz ){
        Object o = null;
        try {
            if (source == null) return null;
            if (clazz == null) return null;
             o = clazz.newInstance();
            BeanUtils.copyProperties(source,o );
        } catch (Exception e) {
            log.error("EntityUtils--> beanToBean fail.",e);
        }
        return o;
    }
}
